<?php
namespace App\Tools\User;

use App\Fishing;
use App\Models\Coupon\Coupon;
use App\Models\Coupon\UserCoupon;
use Carbon\Carbon;
use Doctrine\DBAL\Schema\Table;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Ramsey\Uuid\Uuid;


class User
{
    const TYPE_HLDY = 1;// 欢乐钓鱼
    const TYPE_CQ = 2;//猜拳
    const TYPE_SGDZZ = 3;//水果大作战
    const TYPE_HLGC = 4;//欢乐攻城


    /**
     * 取当前用户是否满足赠送优惠卷
     * @param $user_id
     * @return bool
     */
    public function getUserIsCoupon($user_id, $randId = 0)
    {
        $randId = empty($randId) ? rand(1, 99) : $randId;
        $setUpPrice = 200;
        $time = [
            'startTime' => date('Y-m-d H:i:s', strtotime("-2 day")),
            'endTime' => date('Y-m-d H:i:s', time())
        ];

        //查询用户在48小时内所领取卷金额的总和
        $userCouponPrice = self::getUserTimeCoupon($user_id, $time);
        //用户48小时内在平台玩游戏总收入
        $userPrice = self::getConsumeTotal($user_id, $time);
        //用户实际输钱>=二百以上  (设置金额+随机数+用户游戏总收入+用户卷总金额)
        if (($setUpPrice + $randId + $userPrice + $userCouponPrice <= 0)
            && (UserCoupon::where('user_id', $user_id)->where('created_at', '>=', $time['startTime'])->count() < 3)) {
            $key = "csy:user_" . $user_id;
            if (!Cache::has($key)) {
                Cache::forever($key, $randId);
            }
            return true;
        }
        return false;
    }


    /**
     * 指定用户送优惠卷
     * @param $user_id
     * @return mixed
     */
    public function giveCouponUser($user_id)
    {
        //随机优惠卷发给用户
        $config = [
            1 => ['id' => 1, 'name' => '98', 'rate' => 30],
            2 => ['id' => 2, 'name' => '198', 'rate' => 30],
            3 => ['id' => 3, 'name' => '298', 'rate' => 30],
            4 => ['id' => 4, 'name' => '598', 'rate' => 10],
        ];
        $coupon_id = self::get_rand($config);
        try {

            DB::beginTransaction();
            //查询是否有当前优惠卷信息
            $coupon = self::getCouponOne($coupon_id);
            $uuid = Uuid::uuid1();

            //生成优惠卷信息
            $userCouponModel = new UserCoupon();
            $userCouponModel->coupon_id = $coupon->id;
            $userCouponModel->name = $coupon->name;
            $userCouponModel->user_id = $user_id;
            $userCouponModel->code = $uuid;
            $userCouponModel->min_price = $coupon->min_price;
            $userCouponModel->max_value = $coupon->max_value;
            $userCouponModel->status = 1;
            $userCouponModel->remark = '';
            $userCouponModel->goods_id = $coupon->goods_id;
            $userCouponModel->scope_type = $coupon->scope_type;
            $userCouponModel->created_at = time();
            $userCouponModel->ukey = $user_id . '-' . Carbon::now()->format('YmdHi');
            $userCouponModel->save();

            //用户一分钟内只能请求一次接口
            $last_mktime = UserCoupon::where('id', '<', $userCouponModel->id)->where('user_id', $user_id)
                ->orderBy('id', 'desc')
                ->value('created_at');
            $last_mktime = $last_mktime ? strtotime($last_mktime) : 0;
            if (time() - $last_mktime < 60) {
                DB::rollBack();
                $data['code'] = 1;
                $data['msg'] = '时间冲突，请稍后请求';
                $data['data'] = [];
                return json_encode($data);
            }

            //优惠卷发放总数加1
            DB::table('coupon')
                ->where('id', $coupon_id)
                ->update([
                    'send_num' => $coupon->send_num + 1
                ]);

            //返回优惠卷信息
            $data['code'] = 0;
            $data['data']['code'] = $userCouponModel->code;
            $data['data']['name'] = $userCouponModel->name;
            $data['data']['status'] = $userCouponModel->status;
            $data['data']['max_value'] = $userCouponModel->max_value * 100;
            $data['data']['remark'] = "可用于兑换" . ($userCouponModel->max_value * 100) . "小妖币以下的商品";
            DB::commit();
            return json_encode($data);

        } catch (\Exception $e) {
            DB::rollBack();
            $data['code'] = 1;
            $data['msg'] = '网络繁忙，请稍候再试';
            $data['data'] = [];
            return json_encode($data);
        }
    }


    /**
     * 取得当前优惠卷的小妖币金额
     * @param $coupon_code 优惠卷编码
     * @param $xyb 小妖币
     * @param $goods_id 商品ID
     * @param $order_id 订单ID
     * @return int
     */
    public function getCouponXyb($coupon_code, $xyb, $goods_id, $order_id, &$coupon_id)
    {
        $xybPrice = 0;
        $userCoupon = DB::table('user_coupon')
            ->select('max_value', 'scope_type', 'goods_id', 'id', 'coupon_id')
            ->where([
                ['code', $coupon_code],
                ['status', 1],
            ])
            ->whereIn('scope_type', [1, 2])
            ->first();

        if (empty($userCoupon)) {
            return -1;
        } else {
            //如果当前优惠卷为赠送类型 && 实用于当前商品
            if ($userCoupon->scope_type == 2 && $userCoupon->goods_id == $goods_id) {
                $xybPrice = 0;
                $orderDiscountPrice = $xyb;
            } elseif (($userCoupon->max_value) >= $xyb) {//当优惠卷金额大于|| 等于商品金额时 实际按商品金额计算
                $xybPrice = 0;
                $orderDiscountPrice = $xyb;
            } else {
                return -1;
            }

            //用户优惠卷改为已使用
            DB::table('user_coupon')
                ->where('id', $userCoupon->id)
                ->update([
                    'status' => 2,
                    'order_promotion_price' => $orderDiscountPrice,
                    'order_number' => $order_id
                ]);
            //优惠卷使用数据加1
            DB::table('coupon')
                ->where('id', $userCoupon->coupon_id)
                ->increment('use_num', 1);

            $coupon_id = $userCoupon->id;

            return $xybPrice;
        }
    }


    /**
     * 取得优惠卷信息
     * @param $coupon_id
     * @return mixed
     */
    public function getCouponOne($coupon_id)
    {
        return DB::table('coupon')
            ->where('id', $coupon_id)
            ->orderBy('id', 'desc')
            ->first();
    }

    /**
     * 取得用户在一段时间内领卷的总金额
     * @param $user_id
     * @return mixed
     */
    public function getUserTimeCoupon($user_id,$time)
    {
        return DB::table('user_coupon')
            ->where('user_id', $user_id)
            ->where([
                ['created_at','>=',$time['startTime']],
                ['created_at','<=',$time['endTime']]
            ])
            ->sum('max_value');
    }


    /**
     * 取得平台消息总金额
     * @param int $user_id 用户ID
     * @param array $time 时间段
     * @param int $type 游戏类型
     * @return int
     */
    public function getConsumeTotal($user_id = null, $time = array(), $type = null)
    {
        //统计指定游戏总金额
        if (!empty($type)) {
            switch ($type) {
                case self::TYPE_HLDY:
                    $data = self::getHldyTotal($user_id, $time);
                    break;
                case self::TYPE_CQ:
                    $data = self::getCqTotal($user_id, $time);
                    break;
                case self::TYPE_SGDZZ:
                    $data = self::getSgdzzTotal($user_id, $time);
                    break;
                case  self::TYPE_HLGC:
                    $data = self::getHlgcTotal($user_id, $time);
                    break;
                default:
                    break;
            }

        } else {

            //统计全部游戏总金额
            $hldyTotal = self::getHldyTotal($user_id, $time);
            $cqTotal = self::getCqTotal($user_id, $time);
            $sgdzzTotal = self::getSgdzzTotal($user_id, $time);
            $hlgcTotal = self::getHlgcTotal($user_id, $time);
            $data = $hldyTotal + $cqTotal + $sgdzzTotal + $hlgcTotal;
        }
        return $data;
    }


    /**
     *  取得欢乐钓鱼总金额
     * @param null $user_id 用户ID
     * @param array $time 消费时间段
     * $time = [
     * 'startTime'=>'开始时间',
     * 'endTime'=>'结束时间'
     * ]
     * @return int
     */
    public function getHldyTotal($user_id = null, $time = array())
    {
        $where = ' where 1=1 ';
        if (!empty($user_id)) {
            $where .= ' and mid=' . $user_id;
        }
        if (!empty($time) && is_array($time)) {
            if (!empty($time['startTime'])) {
                $where .= ' and created_at>=' . "'{$time['startTime']}'";
            }
            if (!empty($time['endTime'])) {
                $where .= ' and created_at<=' . "'{$time['endTime']}'";
            }
        }
        $data = json_decode(json_encode(DB::select("SELECT sum(sh_jb-xg_jb) as sum from pan_fishing" . $where)), true);
        return isset($data[0]['sum']) ? $data[0]['sum'] : 0;
    }


    /**
     * 水果大作战总金额
     * @param null $user_id 用户ID
     * @param array $time 消费时间段
     * $time = [
     * 'startTime'=>'开始时间',
     * 'endTime'=>'结束时间'
     * ]
     * @return int
     */
    public function getSgdzzTotal($user_id = null, $time = array())
    {
        $where = ' where unpay=0 ';
        if (!empty($user_id)) {
            $where .= ' and user_id=' . $user_id;
        }
        if (!empty($time) && is_array($time)) {
            if (!empty($time['startTime'])) {
                $where .= ' and created_at>=' . "'{$time['startTime']}'";
            }
            if (!empty($time['endTime'])) {
                $where .= ' and created_at<=' . "'{$time['endTime']}'";
            }
        }

        $win_data = json_decode(json_encode(DB::select("SELECT sum(gold) as sum from game_sgdzz_order_detail_log" . $where . ' and is_win=1')), true);
        $transport_data = json_decode(json_encode(DB::select("SELECT sum(gold) as sum from game_sgdzz_order_detail_log" . $where . ' and is_win=0')), true);
        $win = isset($win_data[0]['sum']) ? $win_data[0]['sum'] : 0;
        $transport = isset($transport_data[0]['sum']) ? $transport_data[0]['sum'] : 0;
        return $win - $transport;
    }


    /**
     * 猜拳总金额
     * @param null $user_id 用户ID
     * @param array $time 消费时间段
     * $time = [
     * 'startTime'=>'开始时间',
     * 'endTime'=>'结束时间'
     * ]
     * @return int
     */
    public function getCqTotal($user_id = null, $time = array())
    {
        $where = ' where 1=1 ';
        if (!empty($user_id)) {
            $where .= ' and user_id=' . $user_id;
        }
        if (!empty($time) && is_array($time)) {
            if (!empty($time['startTime'])) {
                $where .= ' and created_time>=' . "'{$time['startTime']}'";
            }
            if (!empty($time['endTime'])) {
                $where .= ' and created_time<=' . "'{$time['endTime']}'";
            }
        }
        $win_data = json_decode(json_encode(DB::select("SELECT sum(bet_xyb) as sum from game_cq_record_log" . $where . ' and bet_result=1')), true);
        $transport_data = json_decode(json_encode(DB::select("SELECT sum(bet_xyb) as sum from game_cq_record_log" . $where . ' and bet_result=2')), true);
        $win = isset($win_data[0]['sum']) ? $win_data[0]['sum'] : 0;
        $transport = isset($transport_data[0]['sum']) ? $transport_data[0]['sum'] : 0;
        return $win - $transport;
    }

    /**
     * 欢乐攻城总金额
     * @param null $user_id 用户ID
     * @param array $time 消费时间段
     * $time = [
     * 'startTime'=>'开始时间',
     * 'endTime'=>'结束时间'
     * ]
     * @return int
     */
    public function getHlgcTotal($user_id = null, $time = array())
    {
        $where = ' where 1=1 ';
        if (!empty($user_id)) {
            $where .= ' and user_id=' . $user_id;
        }
        if (!empty($time) && is_array($time)) {
            if (!empty($time['startTime'])) {
                $where .= ' and created_time>=' . "'{$time['startTime']}'";
            }
            if (!empty($time['endTime'])) {
                $where .= ' and created_time<=' . "'{$time['endTime']}'";
            }
        }
        $data = json_decode(json_encode(DB::select("SELECT sum(get_xyb-bet_xyb) as sum from game_hlgc_record_log" . $where)), true);
        return isset($data[0]['sum']) ? $data[0]['sum'] : 0;
    }

    //随机算法
    private function get_rand($rand)
    {
        $result = '';
        //概率数组的总概率精度
        $sum = 0;
        foreach ($rand as $v) {
            $sum += $v['rate'] * 100;
        }

        //概率数组循环
        foreach ($rand as $v) {
            $rate = $v['rate'] * 100;
            //抽取随机数
            $rand_num = mt_rand(1, $sum);
            if ($rand_num <= $rate) {
                //得出结果
                $result = $v['id'];
                break;
            } else {
                $sum -= $rate;
            }
        }

        unset ($rand);
        return $result;
    }


}